import React, { useEffect, useState } from 'react'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import { Flex, message, Upload, Modal, Form, Input, Select, Button } from 'antd'
import type { GetProp, UploadProps } from 'antd'
import { useSelector, useDispatch } from 'react-redux'
import styles from './Userinfo.module.scss'
import type{ RootState } from '@/store'
import { getUserInfoApi } from '@/service/index'
import { setUserInfo } from '@/store/models/user'

// 编辑用户接口
import { editUserApi } from '../../service/index'

// 定义文件类型，用于上传组件
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0]

/**
 * 将图片文件转换为Base64编码
 * @param img 图片文件
 * @param callback 转换完成后的回调函数
 */
const getBase64 = (img: FileType, callback: (url: string) => void) => {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result as string))
  reader.readAsDataURL(img)
}

/**
 * 上传前的校验函数
 * @param file 待上传的文件
 * @returns 返回是否通过校验
 */
const beforeUpload = (file: FileType) => {
  // 校验文件类型是否为JPG或PNG
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传JPG/PNG文件!')
  }
  // 校验文件大小是否小于2MB
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过2MB!')
  }
  return isJpgOrPng && isLt2M
}


// 主组件
const App: React.FC = () => {
  // 状态管理
  const [loading, setLoading] = useState(false) // 上传加载状态
  const [imageUrl, setImageUrl] = useState<string>() // 头像图片URL
  const [isModalOpen, setIsModalOpen] = useState(false) // 控制编辑模态框显示
  const [form] = Form.useForm() // 表单实例
  const dispatch = useDispatch() 

  // 获取用户信息
  const getUserInfo = async()=>{
    try {
      const res = await getUserInfoApi()
      if(res.data.code === 0){
        dispatch(setUserInfo(res.data.data))
      } else {
        message.error(res.data.msg)
      }
    } catch (error) {
      console.log(error)
    }
  }

  const editUser = async(parms:any)=>{
    try {
      const res = await editUserApi(parms)
      if(res.data.code === 0){
        message.success('修改成功')
        getUserInfo()
      } else {
        message.error(res.data.msg)
      }
    } catch (error) {
      console.log(error)
    }
    
  }
  // 用户id
  const userInfos = useSelector((state: RootState) => state.userStore.userInfo)

  // 显示编辑模态框
  const showModal = () => {
    setIsModalOpen(true)
  }
  useEffect(()=>{
    setImageUrl(userInfos?.avatar)
  },[userInfos])

  // 提交表单处理
  const handleOk = () => {
    form.validateFields().then(values => {
      editUser({...values,id:userInfos?._id,age:Number(values.age),sex:Number(values.sex)})
      setIsModalOpen(false) // 关闭模态框
    })
  }

  // 重置表单处理
  const handleReset = () => {
    form.resetFields() // 清空表单所有字段
  }

  // 关闭模态框处理
  const handleClose = () => {
    setIsModalOpen(false) // 仅关闭模态框，不重置表单
  }
  const getAvatar=async(id:any, avatar:any)=>{
    try {
      const res = await editUserApi({id,avatar})
      if(res.data.code === 0){
        message.success('修改成功')
        getUserInfo() 
      } else {
        message.error(res.data.msg) 
      } 
    } catch (error) {
      console.log(error)
    }
  }
  // 上传状态变更处理
  const handleChange: UploadProps['onChange'] = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true) // 上传中显示加载状态
      return
    }
    if (info.file.status === 'done') {
      // 获取图片base64编码
      getBase64(info.file.originFileObj as FileType, (url) => {
        setLoading(false) // 上传完成取消加载状态
        setImageUrl(url) // 设置图片URL
      })
      getAvatar(userInfos?._id,info.file.response.data.url)
    }
  }

  // 上传按钮组件
  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}  >上传头像</div>
    </button>
  )

  return (
    <>
      {/* 个人信息展示区域 */}
      <Flex gap="middle" wrap className={styles['picture-head']}>
        <div className={styles['picture-top']}>个人信息</div>
        <div className={styles['picture-bottom']}>
          {/* 头像上传组件 */}
          <Upload
            name="avatar"
            listType="picture-card"
            className={styles['avatar-uploader']}
            showUploadList={false}
            action="/api/profile"
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {imageUrl ? <img src={imageUrl} alt="头像" style={{ width: '100%', height:'100%' }} /> : uploadButton}
          </Upload>
          
          {/* 个人信息展示 */}
          <div className={styles['picture-information']}>
            <div>姓名：{userInfos?.username}</div>
            <div>年龄：{userInfos?.age}</div>
            <div>性别：{userInfos?.sex==0 ? '男': '女'}</div>
          </div>
          <div className={styles['picture-address']}>邮箱：{userInfos?.email}</div>
          <button className={styles['picture-button']} onClick={showModal}>点击编辑</button>
        </div>  
      </Flex>

      {/* 编辑个人信息模态框 */}
      <Modal 
        title="编辑个人信息" 
        open={isModalOpen} 
        onOk={handleOk} 
        onCancel={handleClose}
        footer={[
          <Button key="reset" onClick={handleReset}>重置</Button>,
          <Button key="submit" type="primary" onClick={handleOk}>提交</Button>
        ]}
      >
        {/* 表单区域 */}
        <Form form={form} layout="vertical" initialValues={{...userInfos}}>
          <Form.Item name="username" label="姓名">
            <Input placeholder="请输入姓名" allowClear />
          </Form.Item>
          <Form.Item 
            name="age" 
            label="年龄"
            rules={[
              { 
                type: 'number', 
                min: 0, 
                message: '年龄不能小于0',
                transform: value => value === '' ? undefined : Number(value) // 添加transform处理空字符串
              }
            ]}
          >
            <Input type="number" placeholder="请输入年龄" allowClear />
          </Form.Item>
          <Form.Item name="sex" label="性别">
            <Select placeholder="请选择性别" allowClear>
              <Select.Option value="0">男</Select.Option>
              <Select.Option value="1">女</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item  
            name="email" 
            label="邮箱"
            rules={
              [
                { type: 'email', message: '请输入正确的邮箱地址' }
              ]
            }
          >
            <Input placeholder="请输入邮箱" allowClear />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}

export default App